package com.igeek.d0618.test10;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhiyu
 * @Date:20:05
 * @DESC:
 */
public class BeanFactory {
    private static Map<String, Object> map = new HashMap<>();

    static {
        // 在类加载时初始化 BeanFactory
        loadObjects();
    }

    private static void loadObjects() {
        try (
                BufferedReader reader = new BufferedReader(new FileReader("src/com/igeek/d0618/test10/objects.txt"))
                ) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) {
                    continue; // 忽略空行和注释行
                }
                String[] tokens = line.split("=");
                if (tokens.length == 2) {
//                    String key = tokens[0].trim();
                    String className = tokens[1].trim();
                    Class<?> clazz = Class.forName(className);
                    String simpleName = clazz.getSimpleName();
                    Object instance = clazz.getDeclaredConstructor().newInstance();
                    map.put(simpleName, instance);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从 objects.txt 加载对象时发生错误", e);
        }
    }

    public static void main(String[] args) {
        BeanFactory beanFactory = new BeanFactory();
        Student student = beanFactory.getBean("Student", Student.class); // 通过键名获取对象
        System.out.println(student); // 假设 Student 类已重写 toString()
    }

    public <T> T getBean(String key, Class<T> type) {
        Object object = map.get(key);
        if (object == null) {
            throw new IllegalArgumentException("找不到键为 " + key + " 的对象");
        }
        // 类型转换应该是安全的，因为对象存储在映射中的方式
        return type.cast(object);
    }
}